<template>
    <div class="main" style="height: 824px">
        <div style="margin: 5px">
            <el-input v-model="no" placeholder="请输入名字" :suffix-icon="Search" style="width: 200px"
                @keyup.enter.native="loadPost"></el-input>
            <el-select v-model="sex" filterable placeholder="请选择性别" style="width: 200px; margin-left: 5px">
                <el-option v-for="item in sexs" :key="item.value" :label="item.label" :value="item.value"></el-option>
            </el-select>
            <el-button type="primary" style="margin-left: 5px" @click="loadPost">查询</el-button>
            <el-button type="danger" style="margin-left: 5px" @click="resetParam">重置</el-button>
            <el-button type="success" style="margin-left: 5px" @click="add">新增</el-button>
        </div>
        <el-table :data="tableData" :header-cell-style="{ background: '#f3f6fd', color: '#555' }" :border="true">
            <el-table-column prop="id" label="ID" />
            <el-table-column prop="roleLevel" label="角色">
                <template v-slot:default="scope">
                    <el-tag
                        :type="scope.row.roleLevel === 0 ? 'danger' : (scope.row.roleLevel === 1 ? 'primary' : 'success')"
                        disable-transitions>
                        {{ scope.row.roleLevel === 0 ? '超级管理员' : (scope.row.roleLevel === 1 ? '管理员' : '普通用户') }}
                    </el-tag>
                </template>
            </el-table-column>
            <el-table-column prop="no" label="账号" />
            <el-table-column prop="pwd" label="密码" />
            <el-table-column prop="name" label="姓名" />
            <el-table-column prop="sex" label="性别">
                <template v-slot:default="scope">
                    <el-tag :type="scope.row.sex === 0 ? 'danger' : (scope.row.sex === 1 ? 'primary' : 'success')"
                        disable-transitions>
                        {{ scope.row.sex === 0 ? '未知' : (scope.row.sex === 1 ? '男' : '女') }}
                    </el-tag>
                </template>
            </el-table-column>
            <el-table-column prop="age" label="年龄" />
            <el-table-column prop="phone" label="电话" />
            <el-table-column prop="" label="操作">
              <template v-slot:default="scope">
                <el-button size="small" type="success" @click="edit(scope.row)">编辑</el-button>
                <el-popconfirm title="你确定要删除这个吗?" @confirm="del(scope.row.id)">
                  <template #reference>
                    <el-button size="small" type="danger">删除</el-button>
                  </template>
                </el-popconfirm>
              </template>
            </el-table-column>
        </el-table>
        <el-pagination v-model:current-page="currentPage" v-model:page-size="pageSize" :page-sizes="[17]" :small="small"
            :disabled="disabled" :background="background" layout="total, sizes, prev, pager, next, jumper"
            :total="total" @size-change="handleSizeChange" @current-change="handleCurrentChange"
            style="bottom: 20px; position: fixed; margin-left: 5px; z-index: 2" />
        <el-dialog class="el-dialog" v-model="centerDialogVisible" :title="title" width="400px" center @close="resetForm">
            <el-form :model="form" label-width="auto" style="width: 80%; margin-left: 40px;" :rules="rules"
                ref="formRef">
                <el-form-item label="账号" prop="no">
                    <el-input v-model="form.no" />
                </el-form-item>
                <el-form-item label="姓名" prop="name">
                    <el-input v-model="form.name" />
                </el-form-item>
                <el-form-item label="性别" prop="sex">
                    <el-radio-group v-model="form.sex">
                        <el-radio :value="0">未知</el-radio>
                        <el-radio :value="1">男</el-radio>
                        <el-radio :value="2">女</el-radio>
                    </el-radio-group>
                </el-form-item>
                <el-form-item label="年龄" prop="age">
                    <el-input-number v-model="form.age" :min="1" :max="150" style="width: 500px;" />
                </el-form-item>
                <el-form-item label="密码" prop="pwd">
                    <el-input v-model="form.pwd" type="password" placeholder="请输入" show-password />
                </el-form-item>
                <el-form-item label="电话" prop="phone">
                    <el-input v-model="form.phone" />
                </el-form-item>
            </el-form>
            <template #footer>
                <div class="dialog-footer">
                    <el-button type="primary" @click="centerDialogVisible = false">取消</el-button>
                    <el-button type="danger" @click="resetForm">重置</el-button>
                    <el-button type="success" @click="save">确定</el-button>
                </div>
            </template>
        </el-dialog>
    </div>
</template>

<script setup>
import { onBeforeMount, ref } from 'vue';
import axios from 'axios';
import { httpUrl } from '../../main.js';
import { Search } from '@element-plus/icons-vue';
import { ElMessage } from 'element-plus';

const currentPage = ref(1);
const pageSize = ref(17);
const small = ref(false);
const background = ref(false);
const disabled = ref(false);
const total = ref(0);
const tableData = ref();
const no = ref('');
const noCompare = ref();
const sex = ref('');
const sexs = ref([
    {
        value: '0',
        label: '未知'
    },
    {
        value: '1',
        label: '男'
    },
    {
        value: '2',
        label: '女'
    },
]);
const centerDialogVisible = ref(false);
const formRef = ref(null);
const form = ref({
    id: "",
    no: null,
    pwd: '',
    name: '',
    sex: 0,
    age: 25,
    phone: '',
    roleLevel: 2
});
const resetForm = function () {
    form.value.id = ""
    form.value.no = null
    form.value.pwd = ""
    form.value.age = 25
    form.value.sex = 0
    form.value.phone = ""
    form.value.roleLevel = 2
    form.value.name = ""
    // formRef.value.resetFields()
}
const rules = ref({
    no: [
        { required: true, message: '请输入账号', trigger: 'blur' },
        { min: 3, max: 20, message: '账号长度不能小于3个字符,不能大于20字符', trigger: 'blur' },
        {
            validator: (rule, value, callback) => {
                if (form.value.no) {
                  if(title.value === "新增") {
                    try {
                      axios.get(httpUrl + '/user/findByNo?no=' + form.value.no).then((res) => res.data).then((res) => {
                        console.log(res);
                        if (res.code != 200) {
                          callback()
                        } else {
                          callback(new Error("账号已存在"))
                        }
                      });
                    } catch (error) {
                      console.log(error);
                    }
                  }
                  if (title.value === "编辑") {
                    if(noCompare.value === form.value.no) {
                      console.log(id.value)
                      callback()
                    }else{
                      try {
                        axios.get(httpUrl + '/user/findByNo?no=' + form.value.no).then((res) => res.data).then((res) => {
                          console.log(res);
                          if (res.code != 200) {
                            callback()
                          } else {
                            callback(new Error("账号已存在"))
                          }
                        });
                      } catch (error) {
                        console.log(error);
                      }
                    }
                  }
                }
            }, trigger: 'blur'
        }
    ],
    name: [
        { required: true, message: '请输入姓名', trigger: 'blur' },
        { min: 2, max: 100, message: '姓名长度不能小于2个字符,不能大于100字符', trigger: 'blur' },
    ],
    pwd: [
        { required: true, message: '请输入密码', trigger: 'blur' },
        { min: 6, max: 30, message: '密码长度不能小于6个字符,不能大于30字符', trigger: 'blur' },
    ],
    age: [
        { type: 'number', message: '年龄必须是一个整数', trigger: 'blur' },
        { min: 1, max: 150, message: "年龄在1~150之间", trigger: 'blur' },
    ],
    phone: [
        { required: true, message: '请输入电话', trigger: 'blur' },
        { pattern: /^1[3-9]\d{9}$/, message: '请输入有效的电话号码', trigger: 'blur' },
    ],
});
const title = ref('')
const id = ref()

const handleSizeChange = (val) => {
    console.log(`每页${val}条`);
    currentPage.value = 1;
    pageSize.value = val;
    loadPost();
};

const handleCurrentChange = (val) => {
    console.log(`当前页: ${val}`);
    currentPage.value = val;
    loadPost();
};

const resetParam = () => {
    currentPage.value = 1;
    no.value = '';
    sex.value = '';
    loadPost();
};

const add = () => {
    title.value = "新增"
    centerDialogVisible.value = true;
};

const doSave = function () {
  try {
    axios.post(httpUrl + '/user/save', form.value).then((res) => res.data).then((res) => {
      console.log(res);
      if (res.code == 200) {
        ElMessage({
          message: '新增成功',
          type: 'success'
        });
        centerDialogVisible.value = false
        loadPost()
      } else {
        ElMessage.error('新增失败');
        centerDialogVisible.value = false;
      }
    });
  } catch (error) {
    console.log(error);
  }
}

const doMod = function () {
  try {
    axios.post(httpUrl + '/user/update', form.value).then((res) => res.data).then((res) => {
      console.log(res);
      if (res.code == 200) {
        ElMessage({
          message: '编辑成功',
          type: 'success'
        });
        centerDialogVisible.value = false
        loadPost()
      } else {
        ElMessage.error('编辑失败');
        centerDialogVisible.value = false;
      }
    });
  } catch (error) {
    console.log(error);
  }
}

const save = () => {
    formRef.value.validate((valid) => {
        if (valid) {
            console.log('表单验证成功');
            if(form.value.id) {
              doMod()
            }else{
              doSave()
            }
        } else {
          console.log('表单验证失败');
          return false;
        }
        resetForm()
    });
};

const edit = function (row) {
  console.log(row)
  noCompare.value = row.no
  form.value.id = row.id
  form.value.no = row.no
  form.value.pwd = row.pwd
  form.value.age = row.age
  form.value.sex = row.sex
  form.value.phone = row.phone
  form.value.roleLevel = row.roleLevel
  form.value.name = row.name
  title.value = "编辑"
  centerDialogVisible.value = true;
}

const del = function (id) {
  console.log(id)
  try {
    axios.get(httpUrl + '/user/delete?id=' + id).then((res) => res.data).then((res) => {
      console.log(res);
      if (res.code == 200) {
        ElMessage({
          message: '删除成功',
          type: 'success'
        });
        loadPost()
      } else {
        ElMessage.error('删除失败');
      }
    });
  } catch (error) {
    console.log(error);
  }
}

const loadGet = async () => {
    try {
        axios.get(httpUrl + '/user/list').then((res) => res.data).then((res) => {
            console.log(res);
            tableData.value = res;
        });
    } catch (error) {
        console.log(error);
    }
};

const loadPost = async () => {
    try {
        axios.post(httpUrl + '/user/listPage', {
            pageSize: pageSize.value,
            pageNum: currentPage.value,
            param: {
                no: no.value,
                sex: sex.value
            }
        }).then((res) => res.data).then((res) => {
            console.log(res);
            if (res.code == 200) {
                tableData.value = res.data;
                total.value = res.total;
            } else {
                alert('获取数据失败');
            }
        });
    } catch (error) {
        console.log(error);
    }
};

onBeforeMount(async () => {
    await loadPost();
});
</script>

<style scoped>
.el-dialog {
    left: 50%;
    top: 50%;
    transform: translate(-50%, -50%);
}
</style>
